﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Data;
using System.Windows.Forms;

namespace rInvoice
{
    public partial class Contracts : UserControl
    {
        ServerObject mServerObject = null;
        string messageText = string.Empty;

        public Contracts()
        {
            InitializeComponent();
            mServerObject = new ServerObject();
        }     

        private void Contracts_Load(object sender, EventArgs e)
        {
            FillGridView();
        }

        private void FillGridView()
        {
            DataTable gvTable = mServerObject.SelectContractList(false);
            dataGridView1.DataSource = gvTable;
        }

        private void newButton_Click(object sender, EventArgs e)
        {
            ContractsInputPanel AddForm = new ContractsInputPanel();
            AddForm.CreateNew = true;

            DialogResult resultDialog = AddForm.ShowDialog();
            if (resultDialog == DialogResult.OK)
            {
                messageText = "Data was saved";
            }
            else
            {
                messageText = "Sorry, data was not saved";
            }
            MessageBox.Show(messageText);
            FillGridView();
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                int mContractID = 0;

                string contrID = dataGridView1.Rows[e.RowIndex].Cells["ContractID"].Value.ToString();

                int.TryParse(contrID, out mContractID);
                DataRow rowData = mServerObject.SelectContractByID(mContractID);

                ContractsInputPanel contractInputPanel = new ContractsInputPanel();

                contractInputPanel.ContractID = mContractID;
                contractInputPanel.CompanyID = (int)rowData["CompanyID"];
                contractInputPanel.ContractName = rowData["ContractName"].ToString();
                contractInputPanel.Description = rowData["ContractDescription"].ToString();

                try
                {
                    DialogResult resultDialog = contractInputPanel.ShowDialog();
                    if (resultDialog == DialogResult.OK)
                    {
                        messageText = "Data was saved";
                    }
                    else
                    {
                        messageText = "Sorry, data was not saved";
                    }
                    MessageBox.Show(messageText);
                }
                finally
                {
                    FillGridView();
                }
            }
        }

        private void selectButton_Click(object sender, EventArgs e)
        {
            FillGridView();
        }
    }
}
